<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item :label="pageLabel.partnerName" prop="partnerId">
        <DictSearch
            :dictName="dictPartner.dictName"
            :dictType="dictPartner.dictType"
            :isSingle="dictPartner.isSingle"
            :params="dictPartner.params"
            @selectd="dictSelectdParnter1"
        ></DictSearch>
      </el-form-item>

      <el-form-item label="更新时间" style="width: 308px">
        <el-date-picker
            v-model="daterangeUpdateTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:order:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['wms:order:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['wms:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['wms:order:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="库单ID" align="center" prop="id"/>
      <el-table-column label="单据类型" align="center" prop="orderTypeId">
        <template #default="scope">
          <dict-tag :options="wms_order_type" :value="scope.row.orderTypeId"/>
        </template>
      </el-table-column>
      <el-table-column :label="pageLabel.partnerName" align="center" prop="partnerName"/>
      <el-table-column :label="pageLabel.selfWhName" align="center" prop="selfWhName"/>
      <el-table-column :label="pageLabel.otherWhName" align="center" prop="otherWhName"/>
      <el-table-column label="单据状态" align="center" prop="state">
        <template #default="scope">
          <dict-tag :options="sys_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="单据来源" align="center" prop="sourceId"/>
      <el-table-column label="生产厂商" align="center" prop="manufacturerId"/>
      <el-table-column label="申请人" align="center" prop="userApplicantId"/>
      <el-table-column label="审核人" align="center" prop="userAuditorId"/>
      <el-table-column label="发货员" align="center" prop="userDeliveryId"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建者" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="updateBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="180" label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wms:order:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['wms:order:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改跟物品有关的订单对话框 -->
    <el-dialog :title="title" v-model="open" width="980px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item :label="pageLabel.partnerName" prop="partnerId">
              <DictSearch :dictName="dictPartner.dictName" :dictType="dictPartner.dictType"
                          :isSingle="dictPartner.isSingle" :params="dictPartner.params"
                          @selectd="dictSelectdParnter2"></DictSearch>
            </el-form-item>
            <el-form-item label="是否启用" prop="enableFlag">
              <el-switch
                  v-model="form.state"
                  active-text="已审批"
                  inactive-text="未审批"
                  active-value="0"
                  inactive-value="1"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人" prop="userApplicantId">
              <el-input v-model="form.userApplicantId" placeholder="请输入申请人"/>
            </el-form-item>
            <el-form-item :label="pageLabel.selfWhName" prop="otherWhId">
              <DictSearch :dictName="dictPartner.dictName" :dictType="dictPartner.dictType"
                          :isSingle="dictPartner.isSingle" :params="dictPartner.params"
                          @selectd="dictSelectdParnter2"></DictSearch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发货员" prop="userDeliveryId">
              <el-input v-model="form.userDeliveryId" placeholder="请输入发货员"/>
            </el-form-item>
            <el-form-item :label="pageLabel.otherWhName" prop="otherWhId">
              <DictSearch :dictName="dictPartner.dictName" :dictType="dictPartner.dictType"
                          :isSingle="dictPartner.isSingle" :params="dictPartner.params"
                          @selectd="dictSelectdParnter2"></DictSearch>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核人" prop="userAuditorId">
              <el-input v-model="form.userAuditorId" placeholder="请输入审核人"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">物品订单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">

          <el-col :span="1.5">
            <el-form-item label="添加明细" v-if="showAddDetail">
              <DictSearch :dictName="dictGoods.dictName" :dictType="dictGoods.dictType"
                          :isSingle="dictGoods.isSingle" :params="dictGoods.params"
                          @selectd="dictSelectdGoodsLine">
              </DictSearch>
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Check" @click="toggleAddDetail">新增一行</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteWmsOrderLine">明细删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="Check" @click="submitForm">订单保存</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" icon="Close" @click="cancel">订单关闭</el-button>
          </el-col>
        </el-row>
        <el-table :data="computedOrderLinelist" :row-class-name="rowWmsOrderLineIndex"
                  @selection-change="handleWmsOrderLineSelectionChange" ref="wmsOrderLine">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="产品编码" align="center" prop="goodsCode"/>
          <el-table-column label="产品名称" align="center" prop="goodsName"/>
          <el-table-column label="单位" align="center" prop="measureUnit" width="50"/>
          <el-table-column label="数量" prop="quantity" width="80">
            <template #default="scope">
              <el-input v-model="scope.row.quantity" placeholder="请输入入库数量"/>
            </template>
          </el-table-column>
          <el-table-column label="库位ID" prop="areaId" width="80">
            <template #default="scope">
              <el-input v-model="scope.row.areaId" placeholder="请输入库位ID"/>
            </template>
          </el-table-column>
          <el-table-column label="总金额" align="center" prop="totalMoney"/>
          <el-table-column label="优惠金额" prop="discountMoney" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.discountMoney" placeholder="请输入优惠金额"/>
            </template>
          </el-table-column>
          <el-table-column label="应收金额" prop="receivableMoney" width="100">
            <template #default="scope">
              <el-input v-model="scope.row.receivableMoney" placeholder="请输应收金额"/>
            </template>
          </el-table-column>
          <el-table-column label="有效期" prop="expireDate" width="240">
            <template #default="scope">
              <el-date-picker clearable v-model="scope.row.expireDate"
                              type="date" value-format="YYYY-MM-DD" placeholder="请选择有效期">
              </el-date-picker>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
        <el-col :span="6">
          <el-form-item label="合计金额 :" prop="totalMoney">
            <span>{{ computedTotalMoney }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="优惠总金额 :" prop="discountMoney">
            <span>{{ computedTotalDiscount }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="应收总金额 :" prop="receivableMoney">
            <span>{{ computedReceivableMoney }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实收金额 :" prop="money">
            <span>{{  }}</span>
          </el-form-item>
        </el-col>
        </el-row>
        <el-form-item label="订单备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import {addOrder, delOrder, getOrder, listOrder, updateOrder} from "@/api/wms/order";

import { ref } from 'vue'; // 确保引入 ref
const showAddDetail = ref(false);
const {proxy} = getCurrentInstance();
const {
  sys_state,
  fms_account,
  wms_order_type
} = proxy.useDict('sys_state', 'fms_account', 'wms_order_type');

const orderList = ref([]);
const orderLinelist = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedWmsOrderLine = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeUpdateTime = ref([]);

function toggleAddDetail() {
  // 点击 "新增一行" 按钮时切换显示状态
  showAddDetail.value = !showAddDetail.value;
}

const computedOrderLinelist = computed(() => {
  return orderLinelist.value.map(item => {
    const quantity = item.quantity || 0;
    const price = item.price || 0;
    const discountMoney = item.discountMoney || 0;
    const receivableMoney = item.receivableMoney || 0;
    const totalMoney = item.totalMoney || 0;
    // 计算应收金额：数量 * 单价 - 优惠金额
    item.receivableMoney = quantity * price - discountMoney;
    item.totalMoney = quantity * price;


    return item;
  });
});

// 使用计算属性来计算合计金额
const computedTotalMoney = computed(() => {
  return computedOrderLinelist.value.reduce((total, item) => {
    return total + (item.totalMoney || 0);
  }, 0).toFixed(2); // 你可以根据需要格式化合计金额
});

// 使用计算属性来计算合计应收金额
const computedReceivableMoney = computed(() => {
  return computedOrderLinelist.value.reduce((total, item) => {
    return total + (item.receivableMoney || 0);
  }, 0).toFixed(2); // 你可以根据需要格式化合计金额
});

const computedTotalDiscount = computed(() => {
  return computedOrderLinelist.value.reduce((total, item) => {
    const discountMoney = parseFloat(item.discountMoney) || 0; // 尝试将字符串转换为浮点数，如果失败则默认为 0
    return total + discountMoney;
  }, 0).toFixed(2);
});

/*** 订单明细参数 */
const orderType = reactive({
  //
  id: null,
  // 弹出层标题
  name: null
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderTypeId: null,
    selfWhId: null,
    otherWhId: null,
    state: null,
    sourceId: null,
  },
  rules: {}
});
const {queryParams, form, rules} = toRefs(data);
const route = useRoute();
const pageLabel = reactive({
  partnerName: "",
  receivableMoney: "",
  selfWhName:"",
  otherWhName:"",
  money: ""
});

const dictPartner = reactive({
  dictName: "单据编号查找", // 设置单据编号查找的字典名称
  dictType: "md_partner",
  isSingle: true,
  params: {}
});

// 条件搜索的
function dictSelectdParnter1(dicts) {
  dicts.forEach(function (item) {
    queryParams.value.partnerId = item.dictValue;
  });
}

function dictSelectdParnter2(dicts) {
  dicts.forEach(function (item) {
    form.value.partnerId = item.dictValue;
    // dictPartner.params.partnerId = item.dictValue;
  });
}

const dictGoods = reactive({
  dictName: "物品明细查找", // 设置单据编号查找的字典名称
  dictType: "md_goods_line",
  isSingle: false,
  params: {}
});

function dictSelectdGoodsLine(dicts) {
  dicts.forEach(function (item) {
    let line = {};
    line.goodsCode = item.dictValue;
    line.goodsName = item.dictLabel;
    line.price = item.param1;
    line.attrValue = item.param2;
    line.measureUnit = item.param3;
    handleAddWmsOrderLine(line);
  });
}

/** 查询跟物品有关的订单列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeUpdateTime && '' != daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
  });
  loading.value = false;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    lineId: null,
    partnerId: null,
    orderTypeId: route.query.orderTypeId,
    selfWhId: null,
    otherWhId: null,
    state: "1",
    sourceId: null,
    manufacturerId: null,
    userApplicantId: null,
    userAuditorId: null,
    userDeliveryId: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  orderLinelist.value = [];
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeUpdateTime.value = [];
  queryParams.value.params = {};
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // this.title.value = "添加跟物品有关的订单";
  open.value = true;
  title.value = "添加跟物品有关的订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    orderLinelist.value = response.data.lineList;
    open.value = true;
    title.value = "修改物品订单：" + _id;
  });
}

/** 提交按钮 */
function submitForm() {
  debugger;
  if (form.value.id != null) {
    form.value.lineList = orderLinelist.value;
    updateOrder(form.value,).then(response => {
      proxy.$modal.msgSuccess(response.msg);
    });
  } else {
    form.value.lineList = orderLinelist.value;
    addOrder(form.value).then(response => {
      proxy.$modal.msgSuccess(response.msg);
    });
  }
  open.value = false;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除跟物品有关的订单编号为"' + _ids + '"的数据项？').then(function () {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 物品订单明细序号 */
function rowWmsOrderLineIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 物品订单明细添加按钮操作 */
function handleAddWmsOrderLine(row) {
  let obj = {};
  obj.goodsCode = row.goodsCode;
  obj.goodsName = row.goodsName;
  obj.batchCode = "";
  obj.measureUnit = row.measureUnit;
  obj.price = row.price;
  obj.attrValue = row.attrValue;
  obj.quantity = 1;
  obj.areaId = null;
  obj.expireDate = null;
  obj.totalMoney = obj.price * obj.quantity;
  obj.receivableMoney = obj.price * obj.quantity;
  obj.discountMoney = 0;
  obj.money = 0;
  obj.remark = "";
  orderLinelist.value.push(obj);
}

/** 物品订单明细删除按钮操作 */
function handleDeleteWmsOrderLine() {
  if (checkedWmsOrderLine.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的物品订单明细数据");
  } else {
    const wmsOrderLines = orderLinelist.value;
    const checkedWmsOrderLines = checkedWmsOrderLine.value;
    orderLinelist.value = wmsOrderLines.filter(function (item) {
      return checkedWmsOrderLines.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleWmsOrderLineSelectionChange(selection) {
  checkedWmsOrderLine.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wms/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

function initPage() {
  queryParams.value = route.query;
  if (queryParams.value.orderTypeId == 1 || queryParams.value.orderTypeId == 3 || queryParams.value.orderTypeId == 14) {
    pageLabel.partnerName = "客户";
    pageLabel.receivableMoney = "应收金额";
    pageLabel.money = "实收金额";
    pageLabel.otherWhName="乙方仓库";
    pageLabel.selfWhName="对方仓库"
    dictPartner.params = {isCustomer: "0"};
  } else if (queryParams.value.orderTypeId == 2 || queryParams.value.orderTypeId == 4) {
    pageLabel.partnerName = "供应商";
    pageLabel.receivableMoney = "应付金额";
    pageLabel.money = "实付金额";
    pageLabel.otherWhName="乙方仓库";
    pageLabel.selfWhName="对方仓库"
    dictPartner.params = {isSupplier: "0"};
  } else if (queryParams.value.orderTypeId == 100) {
    pageLabel.partnerName = "客 户";
    pageLabel.receivableMoney = "应付金额";
    pageLabel.money = "实付金额";
  }
}

initPage();
getList();
</script>
